package net.jjjshop.common.service.lbt.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.jjjshop.common.constants.ConfConstants;
import net.jjjshop.common.entity.lbt.LbLineClass;
import net.jjjshop.common.entity.lbt.LbLineUp;
import net.jjjshop.common.entity.lbt.LbSysConfigEntity;
import net.jjjshop.common.entity.lbt.LbUserWalletEntity;
import net.jjjshop.common.entity.order.Order;
import net.jjjshop.common.entity.supplier.Supplier;
import net.jjjshop.common.mapper.lbt.LbLineClassMapper;
import net.jjjshop.common.mapper.lbt.LbLineUpMapper;
import net.jjjshop.common.service.lbt.*;
import net.jjjshop.common.service.order.OrderService;
import net.jjjshop.common.service.supplier.SupplierService;
import net.jjjshop.common.service.user.UserService;
import net.jjjshop.common.util.BigDecimalUtil;
import net.jjjshop.framework.common.service.impl.BaseServiceImpl;
import net.jjjshop.framework.util.LoginUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


/**
 * 用户公排 接口实现类
 */

@Service("LbLineClassServiceImpl")
public class LbLineClassServiceImpl extends BaseServiceImpl<LbLineClassMapper, LbLineClass> implements LbLineClassService {

    @Autowired
    private LbLineClassMapper dao;
    @Autowired
    private LbLineUpService lineUpService;

    @Autowired
    private UserBillService userBillService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SupplierService supplierService;
    @Resource
    private LbUserWalletService lbUserWalletService;
    @Resource
    private LbSysConfigService configService;

    @Override
    public List<LbLineClass> queryList() {
        return dao.queryList(LoginUtil.getUserId());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String stopLine(Integer id) {
        LambdaQueryWrapper<Supplier> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Supplier::getShopSupplierId,id);
        Supplier one = supplierService.getOne(wrapper);
        if (null != one){
            if (one.getStatus() == 0&& one.getIsDelete() == 0){
                one.setStatus(3);
                supplierService.updateById(one);
                stopLineUser(id);
                return "200";
            }else {
                return "只有运行状态才可以关闭";
            }
        }
        return "关闭失败";
    }

    @Override
    public List<LbLineClass> selectAll() {
        return dao.queryAll(LoginUtil.getUserId());
    }

    @Override
    public List<LbLineClass> uesLineClass() {
        return dao.useList();
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean freeTzNum() {
        //定时任务来执行
        LambdaQueryWrapper<LbLineUp> wrapper = new LambdaQueryWrapper<>();
        wrapper.le(LbLineUp::getStatus,4);
        List<LbLineUp> list = lineUpService.list(wrapper);
        if (null != list && list.size() >0){
            LbSysConfigEntity lbSysConfigEntity = configService.selectSysConfig();
            BigDecimal sfBl = new BigDecimal(ConfConstants.INTEGRAL_SF);
            if (null != lbSysConfigEntity && null != lbSysConfigEntity.getReleaseBl()){
                sfBl = lbSysConfigEntity.getReleaseBl();
            }
            for (LbLineUp bean: list){
                LambdaQueryWrapper<Order> ws = new LambdaQueryWrapper<>();
                ws.eq(Order::getOrderNo,bean.getOrderId());
                Order order = orderService.getOne(ws);
                LbUserWalletEntity userWalletInfo = lbUserWalletService.getUserWalletInfo(bean.getUid());
                if (null ==userWalletInfo){
                    throw new RuntimeException("用户："+bean.getUid()+"没有查询到钱包");
                }
                if (null != order ){
                    BigDecimal b = order.getPayPrice();
                    if (b.doubleValue() > bean.getIncome().doubleValue()){
                        BigDecimal c =  BigDecimalUtil.subDouble(b,bean.getIncome());
                        if (bean.getFreeNum().doubleValue() < c.doubleValue()){
                            //订单释放数量
                            BigDecimal sfNum =  BigDecimalUtil.mul(c,sfBl);
                            //释放剩余部分
                            BigDecimal bca =  BigDecimalUtil.subDouble(b,bean.getFreeNum());
                            if (bca.doubleValue() > sfNum.doubleValue()){
                               userBillService.saveBill("订单权益卡释放", ConfConstants.COMMISSION_TYPE,1,sfNum,bean.getUid(),null,order.getOrderId());
                                bean.setFreeNum(BigDecimalUtil.addDouble(bean.getFreeNum(),sfNum));
                                userWalletInfo.setScoreFreeze(BigDecimalUtil.subDouble(userWalletInfo.getScoreFreeze(),sfNum));
                            }else{
                                userBillService.saveBill("订单权益卡释放", ConfConstants.COMMISSION_TYPE,1,bca,bean.getUid(),null,order.getOrderId());
                                bean.setFreeNum(BigDecimalUtil.addDouble(bean.getFreeNum(),bca));
                                bean.setStatus(5);
                                userWalletInfo.setScoreFreeze(BigDecimalUtil.subDouble(userWalletInfo.getScoreFreeze(),bca));
                            }
                            lbUserWalletService.updateById(userWalletInfo);
                        }


                    }
                }

            }

            lineUpService.updateBatchById(list);
        }
        return null;
    }

    /**
     * 退回佣金及权益卡
     * @param id
     */
    private void stopLineUser(Integer id){
        LambdaQueryWrapper<LbLineUp> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LbLineUp::getPid,id);
        wrapper.le(LbLineUp::getStatus,1);
        List<LbLineUp> list = lineUpService.list(wrapper);
        if (null != list && !list.isEmpty()){
            for (LbLineUp bean : list){
                LambdaQueryWrapper<Order> ws = new LambdaQueryWrapper<>();
                ws.eq(Order::getOrderNo,bean.getOrderId());
                Order order = orderService.getOne(ws);
                bean.setStatus(4);
                if (null != order ){
                    BigDecimal b = order.getPayPrice();
                    if (b.doubleValue() > bean.getIncome().doubleValue()){
                        BigDecimal c =  BigDecimalUtil.subDouble(b,bean.getIncome());
                        if ( !userBillService.saveBill("店铺关闭返权益卡", ConfConstants.INTEGRAL_DJ,1,c,bean.getUid(),12,order.getOrderId())){
                            throw new RuntimeException("公排关闭异常");
                        }
                    }
                }

            }
            lineUpService.updateBatchById(list);
        }
    }
}
